package com.itboye.jinpuyiyuan.activity.home.finddoctor;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.mobileim.IYWLoginService;
import com.alibaba.mobileim.YWAPI;
import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.YWLoginParam;
import com.alibaba.mobileim.channel.event.IWxCallback;
import com.alibaba.mobileim.channel.util.WxLog;
import com.alibaba.mobileim.channel.util.YWLog;
import com.alibaba.mobileim.contact.IYWContact;
import com.alibaba.mobileim.contact.YWContactFactory;
import com.alibaba.mobileim.conversation.IYWConversationService;
import com.alibaba.mobileim.conversation.IYWConversationUnreadChangeListener;
import com.alibaba.mobileim.conversation.IYWMessageLifeCycleListener;
import com.alibaba.mobileim.conversation.IYWSendMessageToContactInBlackListListener;
import com.alibaba.mobileim.conversation.YWConversation;
import com.alibaba.mobileim.conversation.YWConversationCreater;
import com.alibaba.mobileim.conversation.YWConversationType;
import com.alibaba.mobileim.conversation.YWMessage;
import com.alibaba.mobileim.conversation.YWMessageChannel;
import com.alibaba.mobileim.conversation.YWMessageType;
import com.alibaba.mobileim.gingko.model.tribe.YWTribe;
import com.alibaba.mobileim.gingko.model.tribe.YWTribeMember;
import com.alibaba.mobileim.gingko.presenter.tribe.IYWTribeChangeListener;
import com.alibaba.mobileim.login.IYWConnectionListener;
import com.alibaba.mobileim.login.YWLoginCode;
import com.alibaba.mobileim.login.YWLoginState;
import com.alibaba.mobileim.utility.IMNotificationUtils;
import com.bumptech.glide.Glide;
import com.itboye.jinpuyiyuan.R;
import com.itboye.jinpuyiyuan.activity.login.LoginActivity;
import com.itboye.jinpuyiyuan.app.MyApplication;
import com.itboye.jinpuyiyuan.base.BaseActivity;
import com.itboye.jinpuyiyuan.bean.RegisterDoctorDetail;
import com.itboye.jinpuyiyuan.presenter.BranchAddressPresenter;
import com.itboye.jinpuyiyuan.utils.IMKit.CustomConversationHelper;
import com.itboye.jinpuyiyuan.utils.IMKit.LoginSampleHelper;
import com.itboye.jinpuyiyuan.utils.sputil.Const;
import com.itboye.jinpuyiyuan.utils.sputil.SPUtils;
import com.itboye.jinpuyiyuan.utils.volley.ResultEntity;
import com.itboye.jinpuyiyuan.widget.CircleImageView;
import com.itboye.jinpuyiyuan.widget.ImageCompress;
import com.itboye.jinpuyiyuan.widget.loadingutil.MAlert;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by Administrator on 2017/12/11 0011.
 */

public class DoctorDetailActivity extends BaseActivity implements Observer {
    //title
    private ImageView leftImg,rightImg;
    private TextView leftTv,tvTitle;
    private RelativeLayout rlLeft,toobar;

    private Intent intent;
    private TextView introduce,workStrength,workAddress;
    private TextView consultationTv;//咨询
    private TextView doctorName,doctorProvince,doctorCity,doctorEvaluate;
    private CircleImageView doctorImg;
    private BranchAddressPresenter presenter,presenter1;

    private YWIMKit mIMKit;
    private IYWConversationService mConversationService;
    private Handler mHandler = new Handler(Looper.getMainLooper());

    private IYWTribeChangeListener mTribeChangedListener;
    private IYWConversationUnreadChangeListener mConversationUnreadChangeListener;
    private IYWMessageLifeCycleListener mMessageLifeCycleListener;
    private IYWSendMessageToContactInBlackListListener mSendMessageToContactInBlackListListener;
    private IYWConnectionListener mConnectionListener;

    public static final String SYSTEM_TRIBE_CONVERSATION="sysTribe";
    public static final String SYSTEM_FRIEND_REQ_CONVERSATION="sysfrdreq";
    public static final String RELATED_ACCOUNT = "relatedAccount";
    public static final String TAG = "DoctorDetailActivity";
    private String userid;
    private String password;
    private String tagUid;
    String doctorId;
    private int docId;//判断当前跳转是否从聊天界面跳转过来  1  是  其他 否

    private int online;//在线状态
    private Bitmap logoBit;
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_doctordetail);

        intent=getIntent();
        leftTv.setVisibility(View.GONE);
        rightImg.setVisibility(View.GONE);
        tvTitle.setText(intent.getStringExtra("doctorName"));
        docId=intent.getIntExtra("docId",0);
        doctorId = intent.getStringExtra("doctorId");
        if (docId==1){
            consultationTv.setVisibility(View.GONE);
        }
        Thread thread= new Thread() {
            @Override
            public void run() {
                logoBit=returnBitmap(Const.DoctorImg+doctorId);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        doctorImg.setImageBitmap(logoBit);
                    }
                });
            }
        };
        thread.start();



//        Glide.with(this).load(Const.DoctorImg+doctorId).into(doctorImg);
        userid= (String) SPUtils.get(getApplication(),null,Const.ALIBAICHUAN,"");
        if (userid==null||userid.equals("")){

        }else {
            mIMKit = YWAPI.getIMKitInstance(userid,Const.OPEN_APPKEY);
            mConversationService = mIMKit.getConversationService();
            password=(String) SPUtils.get(getApplication(),null,Const.PASSWORD,"");

        }
//        IYWLoginService loginService = mIMKit.getLoginService();
//        mIMKit.setEnableNotification(true);
//        YWLoginParam loginParam = YWLoginParam.createLoginParam(userid, password);
//        loginService.login(loginParam, new IWxCallback() {
//            @Override
//            public void onSuccess(Object... arg0) {
//                Log.d("login====","success");
//            }
//
//            @Override
//            public void onProgress(int arg0) {
//                // TODO Auto-generated method stub
//            }
//            @Override
//            public void onError(int errCode, String description) {
//                //如果登录失败，errCode为错误码,description是错误的具体描述信息
//                Log.d("login====","description=="+description.toString());
//            }
//        });
        presenter=new BranchAddressPresenter(this);
        presenter.queryDoctorDetail(doctorId);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){
            case R.id.rlLeft:
            case R.id.leftImg:
                this.finish();
                break;

            case R.id.consultationTv:
                //开启单聊模式

                if (userid==null||userid.equals("")){
                  //去登录
                    startActivity(new Intent(this,LoginActivity.class));
                }else {
                    if (online!=1){
                        MAlert.alert("该医生不在线");
                        break;
                    }

                    MyApplication.toUid=doctorId;
//                 mIMKit =YWAPI.getIMKitInstance(userid,Const.OPEN_APPKEY);
                    mIMKit =LoginSampleHelper.getInstance().getIMKit();
//                final String target = "tb_im_u_cb35f8dd40804238caf64c4a845c2f96"; //消息接收者ID
                    final String appkey = Const.OPEN_APPKEY; //消息接收者appKey
//                IYWContact contact = YWContactFactory.createAPPContact(tagUid, appkey);
                    //创建一个与消息接收者的聊天会话，userId：表示聊天对象id
                    final YWConversationCreater conversationCreater = mConversationService.getConversationCreater();
                    YWConversation conversation = conversationCreater.createConversationIfNotExist(tagUid);
                    Intent intent = mIMKit.getChattingActivityIntent(tagUid, appkey);
                    Log.d("imkit==",tagUid);
                    startActivity(intent);

                }

                break;
        }
    }

    @Override
    public void update(Observable o, Object arg) {
        ResultEntity resultEntity = handlerError(arg);
        if (resultEntity!=null){

            if (resultEntity.getEventType()==BranchAddressPresenter.By_HospDoct_detail_success){
//                MAlert.alert("查询成功");
                RegisterDoctorDetail registerDoctorDetail= (RegisterDoctorDetail) resultEntity.getData();
                doctorName.setText(registerDoctorDetail.getNickname());
//                doctorProvince.setText(registerDoctorDetail.getProvince());
//                doctorCity.setText(registerDoctorDetail.getCity());
                doctorEvaluate.setText(registerDoctorDetail.getJob_title());
                introduce.setText(registerDoctorDetail.getDesc());

                workAddress.setText(registerDoctorDetail.getSect_list().get(0).getDept_name());
                workStrength.setText(registerDoctorDetail.getSpecial());
                online=registerDoctorDetail.getOnline_status();
                tagUid=registerDoctorDetail.getAlibaichuan_id();
                Log.d("taguid==",tagUid+"==="+online);

            }else if (resultEntity.getEventType()==BranchAddressPresenter.By_HospDoct_detail_fail){
//                MAlert.alert("医师详情查询失败");
            }
        }
    }


    /**
     * 根据图片的url路径获得Bitmap对象
     * @param url
     * @return
     */
    private Bitmap returnBitmap(String url) {
        URL fileUrl = null;
        Bitmap bitmap = null;

        try {
            fileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            HttpURLConnection conn = (HttpURLConnection) fileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;

    }



}
